<template>
  <CommonDialog
    class="add_form"
    v-model="visible"
    :title="`${roleId ? '编辑' : '新增'}角色`"
    :mask-closable="false"
    :draggable="true"
    :sticky="true"
    :scrollable="true"
    :width="460"
    @cancel="cancel"
    @visible-change="handleVisibleChange"
  >
    <OptionForm
      ref="formRef"
      v-model="formData"
      :fields="formFields"
      :config="formConfig"
    />

    <template #footer>
      <Button @click="cancel">取消</Button>
      <Button
        type="primary"
        @click="submit"
        :loading="loading"
      >立即提交</Button>
    </template>
  </CommonDialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from 'view-ui-plus'
import { sysdicGetByCode, roleAdd, roleEdit } from '@/api/modules/role'
import OptionForm from '@/components/OptionForm/index.vue'
import CommonDialog from '@/components/CommonDialog/index.vue'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载
const loading = ref(false)

// 表单元素ref
const formRef = ref(null)

// 表单数据
const formData = ref({
  name: '',
  portal: '', //默认首页
  callcenter: '', //语音渠道-首页
  quality: '', //质检-首页
  monitorpage: '', //智能监控-首页
  settingpage: '', //客服设置-首页
  servicepage: '', //会话历史-首页
  calloutpage: '' //名单管理-首页
})

// 角色ID
const roleId = ref(undefined)

// 字典选项映射
const optionsMap = ref({
  portal: {
    label: '默认首页',
    code: 'com.dic.desktop.portal',
    options: []
  },
  callcenter: {
    label: '语音渠道-首页',
    code: 'com.dic.homepage.callcenter',
    options: []
  },
  quality: {
    label: '质检-首页',
    code: 'com.dic.homepage.quality',
    options: []
  },
  monitorpage: {
    label: '智能监控-首页',
    code: 'com.dic.homepage.monitor',
    options: []
  },
  settingpage: {
    label: '客服设置-首页',
    code: 'com.dic.homepage.setting',
    options: []
  },
  servicepage: {
    label: '会话历史-首页',
    code: 'com.dic.homepage.agentservice',
    options: []
  },
  calloutpage: {
    label: '名单管理-首页',
    code: 'com.dic.homepage.callout',
    options: []
  }
})

// 表单字段配置
const formFields = computed(() => {
  const fields = {
    name: {
      type: 'input',
      label: '角色',
      required: true,
      placeholder: '请输入角色',
      clearable: true
    }
  }

  // 添加其他选择字段
  Object.entries(optionsMap.value).forEach(([key, item]) => {
    fields[key] = {
      type: 'select',
      label: item.label,
      placeholder: '请选择' + item.label,
      options: item.options || [],
      transfer: true
    }
  })

  return fields
})

// 表单配置
const formConfig = ref({
  labelWidth: 140,
  labelPosition: 'right',
  labelColon: true
})

// 获取字典数据
const getSysdicGetByCodeData = () => {
  // 遍历所有字典项，获取选项数据
  Object.entries(optionsMap.value).forEach(([key, item]) => {
    sysdicGetByCode({
      data: {
        code: item.code
      }
    }).then(({data}) => {
      // 将数据转换为OptionForm组件需要的格式
      item.options = data.map(option => ({
        label: option.name,
        value: option.id
      }))
    })
  })
}

/**
 * 提交表单
 */
const submit = async () => {
  try {
    // 验证表单
    const formData = await formRef.value.validate()

    loading.value = true

    // 调用API提交数据
    await (roleId.value ? roleEdit : roleAdd)({
      data: {
        ...formData,
        id: roleId.value
      }
    })

    Message.success('成功操作')

    emit('submit', roleId.value)
  } catch (error) {
    console.error('提交表单时出错:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

/**
 * 处理对话框可见性变化
 */
const handleVisibleChange = (val) => {
  if (!val) {
    emit('cancel')
  }
}

/**
 * 初始化对话框
 */
const initDialog = data => {
  // 显示对话框
  visible.value = true

  if (data) {
    // 设置角色ID
    roleId.value = data.id

    // 设置表单数据
    Object.keys(formData.value).forEach(key => {
      formData.value[key] = data[key] || ''
    })
  } else {
    // 新增模式，重置角色ID和表单数据
    roleId.value = undefined

    // 重置表单数据
    Object.keys(formData.value).forEach(key => {
      formData.value[key] = ''
    })
  }

  // 清除表单验证状态
  setTimeout(() => {
    if (formRef.value && typeof formRef.value.clearValidate === 'function') {
      formRef.value.clearValidate()
    }
  }, 100)
}

defineExpose({
  initDialog
})

onMounted(() => {
  getSysdicGetByCodeData()
})
</script>

<style scoped lang="scss">
.ivu-input-wrapper,
.ivu-select {
  width: 240px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>